Component({
  properties: {
  },

  data: {
    pageNo: 1,
    hasMore: true,
    remenArray: []
  },

  methods: {
    toClassdetail(e) {
      const id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/pages/kecheng_detail/kechengxiangqing/kechengxiangqing?id=' + id
      });
    },

    // 处理价格数据，保留两位小数
    formatPrice(originalPrice, discount) {
      return (originalPrice * discount).toFixed(2);
    },

    loadHotCourses() {
      if (!this.data.hasMore) return;
      
      wx.showLoading({
        title: '加载中',
      });
      
      wx.request({
        url: 'http://120.26.112.194:80/api/admin/courses/hot',
        method: 'GET',
        data: {
          page: this.data.pageNo,
          pageSize: 6
        },
        success: (res) => {
          console.log('热门课程数据:', res.data);
          if (res.data && res.data.code === 200) {
            const newCourses = res.data.data.list;
            // 处理每个课程的价格
            newCourses.forEach(course => {
              course.discountPrice = this.formatPrice(course.originalPrice, course.discount);
            });
            this.setData({
              remenArray: this.data.pageNo === 1 ? newCourses : [...this.data.remenArray, ...newCourses],
              hasMore: res.data.data.hasNextPage
            });
          }
          wx.hideLoading();
        },
        fail: (error) => {
          console.error('请求失败', error);
          wx.hideLoading();
        }
      });
    }
  },

  pageLifetimes: {
    show() {
      // 页面显示时加载数据
      this.loadHotCourses();
    }
  },

  lifetimes: {
    attached() {
      // 组件加载时加载数据
      this.loadHotCourses();
    }
  },

  // 监听页面的下拉刷新和触底事件
  observers: {
    '**': function() {
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      
      if (currentPage) {
        // 覆盖页面的下拉刷新事件
        currentPage.onPullDownRefresh = () => {
          this.setData({ 
            pageNo: 1,
            hasMore: true 
          }, () => {
            this.loadHotCourses();
            wx.stopPullDownRefresh();
          });
        };

        // 覆盖页面的触底事件
        currentPage.onReachBottom = () => {
          if (this.data.hasMore) {
            this.setData({
              pageNo: this.data.pageNo + 1
            }, () => {
              this.loadHotCourses();
            });
          }
        };
      }
    }
  }
}); 